<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-row :gutter="20">
        <el-col :span="24" align="right">
          <el-form-item label="来料批次" prop="ksCode">
            <el-input
              v-model="queryParams.llCode"
              placeholder="请输入来料批次"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['warehouse:llrk:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['warehouse:llrk:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['warehouse:llrk:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['warehouse:llrk:export']"-->
<!--        >导出-->
<!--        </el-button>-->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="llrkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="来料批次" align="center" prop="llCode" width="180"/>
      <el-table-column label="物料编码" align="center" prop="wlCode"/>
      <el-table-column label="物料名称" align="center" prop="wldaMaterialFile.wlName"/>
      <el-table-column label="物料分类" align="center" prop="wldaMaterialFile.wlTypecode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wl_type" :value="scope.row.wldaMaterialFile.wlTypecode"/>
        </template>
      </el-table-column>
      <el-table-column label="物料规格" align="center" prop="wldaMaterialFile.wlGg"/>
      <el-table-column label="物料单位" align="center" prop="wldaMaterialFile.jldwMeasurementUnit.dwName"/>
      <el-table-column label="收料数量" align="center" prop="total"/>
      <el-table-column label="供应商" align="center" prop="ksMerchants.merchantsName"/>
      <el-table-column label="物料编码" align="center" prop="wlCode"/>
      <el-table-column label="来料时间" align="center" prop="gettime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gettime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleExamine(scope.row)"
            v-hasPermi="['warehouse:llrk:examine']"
            v-if="scope.row.isUse===1"
          >审核
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['warehouse:llrk:edit']"
            v-if="scope.row.isUse===1"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetails(scope.row)"
            v-hasPermi="['warehouse:llrk:submit']"
            v-if="scope.row.isUse===0"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['warehouse:llrk:remove']"
            v-if="scope.row.isUse===1"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleCancel(scope.row)"
            v-hasPermi="['warehouse:llrk:cancel']"
            v-if="scope.row.isUse===0"
          >撤销
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改来料入库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" :inline="true">
        <el-form-item label="供应商" prop="ksMerchants.merchantsName">
          <el-input v-model="form.ksMerchants.merchantsName" placeholder="请选择供应商" readonly
                    @click.native="selectMerchants()" suffix-icon="el-icon-more">
          </el-input>
        </el-form-item>
        <el-form-item label="物料名称" prop="wldaMaterialFile.wlName">
          <el-input v-model="form.wldaMaterialFile.wlName" placeholder="请选择物料" readonly
                    @click.native="selectWldaMaterialFile()" suffix-icon="el-icon-more"/>
        </el-form-item>
        <el-form-item label="物料分类" prop="wldaMaterialFile.wlSortcode">
          <el-select v-model="form.wldaMaterialFile.wlSortcode" placeholder="请选择物料分类" disabled clearable>
            <el-option
              v-for="dict in dict.type.wl_sortcode"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物料规格" prop="isUse">
          <el-input v-model="form.wldaMaterialFile.wlGg" placeholder="请选择物料" readonly/>
        </el-form-item>
        <el-form-item label="收料时间" prop="gettime">
          <el-date-picker clearable
                          v-model="form.gettime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择收料时间">
          </el-date-picker>
        </el-form-item>

        <el-divider content-position="center">来料详情</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddWldaMaterialFile">添加
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteWldaMaterialFile">删除
            </el-button>
          </el-col>
        </el-row>
        <el-table :data="form.llslIncomingMaterialsList" prop="form.llslIncomingMaterialsList"  :row-class-name="rowWldaMaterialFileIndex"
                  @selection-change="handleWldaMaterialFileSelectionChange" ref="llslFile">
          <el-table-column type="selection" width="70" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="70" />
          <el-table-column label="等级" width="170" align="center" prop="llslLevel">
            <template slot-scope="scope">
              <el-input v-model="scope.row.llslLevel" placeholder="请输入物料等级" />
            </template>
          </el-table-column>
          <el-table-column label="入库仓库" prop="ckWarehouse.ckName" width="170" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.ckWarehouse.ckName" placeholder="请选择仓库" readonly
                        @click.native="selectCkWarehouse(scope.row)" suffix-icon="el-icon-more"/>
            </template>
          </el-table-column>
          <el-table-column label="入库数量" prop="innum" width="170" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.innum" placeholder="请输入数量"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--     客商弹框 -->
    <el-dialog :title="PopUpsTitle" :visible.sync="open1" width="40%">
      <el-container>
        <el-header>
          <el-input v-model="queryParams1.wlName" suffix-icon="el-icon-search" @keyup.enter.native="peoUpsQuery"></el-input>
<!--          <el-button type="primary" icon="el-icon-search" size="mini" @click="peoUpsQuery">搜索</el-button>-->
        </el-header>
        <el-main v-if="ksOpen"  v-loading="loading1">
          <!--展示客商信息-->
          <el-table border :data="ksMerchantsList" @row-click="ksHandleRowClick">
            <el-table-column prop="ksCode" label="客商编号" width="140px"></el-table-column>
            <el-table-column prop="merchantsName" label="客商名称"></el-table-column>
            <el-table-column prop="ksLevelCode" label="客商等级"></el-table-column>
          </el-table>
        </el-main>
        <el-main v-if="wlOpen" v-loading="loading1">
          <!--展示物料信息-->
          <el-table border :data="wldaMaterialFileList" @row-click="wlHandleRowClick">
            <el-table-column prop="wlCode" label="物料编号" width="140px"/>
            <el-table-column prop="wlName" label="物料名称"/>
            <el-table-column prop="wlSortcode" label="物料类型">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.wl_sortcode" :value="scope.row.wlSortcode"/>
              </template>
            </el-table-column>
            <el-table-column prop="wlGg" label="物料规格"></el-table-column>
          </el-table>
        </el-main>
        <el-main v-if="ckOpen" v-loading="loading1">
          <!--展示仓库信息-->
          <el-table border :data="CkWarehouseList" @row-click="ckHandleRowClick">
            <el-table-column prop="ckCode" label="仓库编号" width="140px"/>
            <el-table-column prop="ckName" label="仓库名称"/>
            <el-table-column prop="ckTypecode" label="仓库类型">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.ck_type" :value="scope.row.ckTypecode"/>
              </template>
            </el-table-column>
          </el-table>
        </el-main>

        <pagination
          v-show="queryParams1.total>0"
          :total="queryParams1.total"
          :page.sync="queryParams1.pageNum"
          :limit.sync="queryParams1.pageSize"
          @pagination="selectMerchants"
        />
      </el-container>
    </el-dialog>

    <!--  详情弹窗  -->
    <el-dialog title="入库详情" :visible.sync="open2" width="600px" append-to-body>
      <el-form ref="form" :model="form" label-width="120px" style="font-size: 10px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商：" prop="ksMerchants.merchantsName">
              <span>{{ form.ksMerchants.merchantsName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称：" prop="wldaMaterialFile.wlName">
              <span>{{ form.wldaMaterialFile.wlName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物料分类：" prop="wldaMaterialFile.wlSortcode">
                <dict-tag :options="dict.type.wl_sortcode" :value="form.wldaMaterialFile.wlSortcode"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料规格：" prop="wldaMaterialFile.wlGg">
              <span>{{ form.wldaMaterialFile.wlGg }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收料时间：" prop="gettime">
              <span>{{ form.gettime }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">入库详情</el-divider>
        <el-table :data="form.llslIncomingMaterialsList" :row-class-name="rowWldaMaterialFileIndex"
                  @selection-change="handleWldaMaterialFileSelectionChange" ref="llslFile">
          <el-table-column label="序号" align="center" prop="index" />
          <el-table-column label="等级" align="center" prop="llslLevel"/>
          <el-table-column label="入库仓库" prop="ckWarehouse.ckName" align="center"/>
          <el-table-column label="入库数量" prop="innum" align="center"/>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="detailsClear">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {listLlrk, getLlrk, delLlrk, addLlrk, updateLlrk, wlList, ckList, examine,cancel,} from "@/api/warehouse/llrk";
import {listMerchants} from "@/api/jbxx/merchants";

export default {
  name: "Llrk",
  dicts: ['wl_from', 'is_use', 'wl_type', 'wl_sortcode','ck_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      loading1:true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedWldaMaterialFile: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 来料入库表格数据
      llrkList: [],
      // 来料数量表格数据
      LlslIncomingMaterialsList: [],
      //来料数量下标（添加仓库时判断）
      LlslIndex:null,
      // 客商档案表格数据
      ksMerchantsList: [],
      ksOpen:false,
      // 物料档案表格数据
      wldaMaterialFileList: [],
      wlOpen:false,
      // 仓库信息
      CkWarehouseList: [],
      ckOpen:false,
      // 弹出层标题
      PopUpsTitle: null,
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（添加参数选择）
      open1: false,
      // 详情弹出层
      open2: false,
      // 弹床标题
      title: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        llCode: null,
        gettime: null
      },
      // 查询客商参数
      queryParams1: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        wlName:null,
        merchantsName:null,
        ckName:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        'ksMerchants.merchantsName': [
          {required: true, message: "客商不能为空", trigger: "blur"}
        ],
        'wldaMaterialFile.wlName': [
          {required: true, message: "物料不能为空", trigger: "blur"}
        ],
        gettime: [
          {required: true, message: "收料时间不能为空", trigger: "blur"}
        ],
      }
      //
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询来料入库列表 */
    getList() {
      this.reset();
      listLlrk(this.queryParams).then(response => {
        this.llrkList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        llCode: null,
        ksCode: null,
        wlCode: null,
        getTime: null,
        isUse: null,
        isDelete: null,
        total: null,
        wldaMaterialFile: {
          wlName: null,
          wlCode: null,
          wlGg:null,
          wlSortcode:''
        },
        ksMerchants: {
          ksCode: null,
          merchantsName: null
        },
        llslIncomingMaterialsList: []
      };
      this.LlslIncomingMaterialsList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.llCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加来料入库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const llCode = row.llCode || this.ids
      getLlrk(llCode).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改来料入库";
      });
    },
    handleDetails(row){
      // this.reset();
      const llCode = row.llCode
      getLlrk(llCode).then(response => {
        this.form = response.data;
        this.open2 = true;
      });
    },
    detailsClear(){
      this.reset();
      this.open2 = true;
    },
    /** 撤销 */
    handleCancel(row){
      const llCode = row.llCode
      this.$modal.confirm('是否撤销来料编号为"' + llCode + '"的数据项？').then(function () {
        return cancel(llCode);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤销成功");
      }).catch(() => {
      });
    },
    /** 审核*/
    handleExamine(row){
      const llCodes = row.llCode;
      this.$modal.confirm('是否确认审批来料入库编号为"' + llCodes + '"的数据项？').then(function () {
        return examine(llCodes);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("审批成功");
      }).catch(() => {
      });
    },
    /** 弹窗 */
    PopUpsShow() {
      this.open1 = true
      this.loading1 = true
      // this.ksMerchantsList = null;
      // this.wldaMaterialFileList= null;
      // this.CkWarehouseList = null;
      this.ksOpen = false
      this.wlOpen = false
      this.ckOpen = false
    },
    /**
     * 查询-选择客商
     * */
    selectMerchants() {
      this.PopUpsShow()
      this.ksOpen = true
      this.PopUpsTitle = "选择客商";
      listMerchants(this.queryParams1).then(response => {
        this.ksMerchantsList = response.rows;
        console.log(this.ksMerchantsList)
        this.queryParams1.total = response.total;
        this.loading1 = false
        this.queryParams1.ckName=null;
        this.queryParams1.merchantsName=null;
        this.queryParams1.wlName=null;
      });
    },
    ksHandleRowClick(row){
      this.open1 = false
      this.form.ksCode=row.ksCode;
      this.form.ksMerchants.ksCode=row.ksCode;
      this.form.ksMerchants.merchantsName=row.merchantsName;
    },
    /**
     * 查询-选择物料
     * */
    selectWldaMaterialFile() {
      this.PopUpsShow()
      this.wlOpen = true
      this.PopUpsTitle = "选择物料";
      wlList(this.queryParams1).then(response => {
        this.wldaMaterialFileList = response.rows;
        console.log(this.ksMerchantsList)
        this.queryParams1.total = response.total;
        this.loading1 = false
        this.queryParams1.ckName=null;
        this.queryParams1.merchantsName=null;
        this.queryParams1.wlName=null;
      });
    },
    wlHandleRowClick(row){
      this.open1 = false
      this.form.wlCode=row.wlCode;
      this.form.wldaMaterialFile.wlCode=row.wlCode;
      this.form.wldaMaterialFile.wlName=row.wlName;
      this.form.wldaMaterialFile.wlGg=row.wlGg;
      this.form.wldaMaterialFile.wlSortcode=row.wlSortcode;
    },
    /**
     * 查询-选择仓库
     * */
    selectCkWarehouse(row) {
      this.PopUpsShow()
      this.ckOpen = true
      this.PopUpsTitle = "选择仓库";
      this.LlslIndex=row.index-1;
      ckList(this.queryParams1).then(response => {
        this.CkWarehouseList = response.rows;
        this.loading1 = false
        this.queryParams1.total = response.total;
      });
    },
    ckHandleRowClick(row){
      this.open1 = false
      this.form.llslIncomingMaterialsList[this.LlslIndex].ckCode=row.ckCode
      this.form.llslIncomingMaterialsList[this.LlslIndex].ckWarehouse.ckCode=row.ckCode
      this.form.llslIncomingMaterialsList[this.LlslIndex].ckWarehouse.ckName=row.ckName
    },
    /** 弹窗搜索*/
    peoUpsQuery(){
      this.queryParams1.ckName=this.queryParams1.wlName
      this.queryParams1.merchantsName=this.queryParams1.wlName
      if(this.ksOpen){
        this.selectMerchants()
      }else if(this.wlOpen){
        this.selectWldaMaterialFile()
      } if(this.ckOpen){
        this.loading1 = true
        ckList(this.queryParams1).then(response => {
          this.CkWarehouseList = response.rows;
          this.queryParams1.total = response.total;
          this.loading1 = false
          this.queryParams1.ckName=null;
          this.queryParams1.merchantsName=null;
          this.queryParams1.wlName=null;
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 获取表格长度，判断是否有添加数据
          let llslLength=this.form.llslIncomingMaterialsList.length
          if(llslLength===0){
            this.$message.error('请填写来料信息');
            return;// 没有数据阻止提交
          }
          // 遍历表格数据，检查每行数据是否符合要求
          for (let i = 0; i < llslLength; i++) {
            const rowData = this.form.llslIncomingMaterialsList[i];
            if (!rowData.llslLevel || !rowData.ckWarehouse.ckName || !rowData.innum) {
              this.$message.error('请填写完整的来料信息');
              return; // 阻止提交
            }
          }
          if (this.form.llCode != null) {
            updateLlrk(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLlrk(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const llCodes = row.llCode || this.ids;
      this.$modal.confirm('是否确认删除来料入库编号为"' + llCodes + '"的数据项？').then(function () {
        return delLlrk(llCodes);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 物料档案序号 */
    rowWldaMaterialFileIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 物料档案添加按钮操作 */
    handleAddWldaMaterialFile() {
      let obj = {};
      let ck = {};
      obj.llslLevel = "";
      ck.ckName = "";
      obj.ckWarehouse = ck;
      obj.innum = "";
      this.form.llslIncomingMaterialsList.push(obj);
    },
    /** 物料档案删除按钮操作 */
    handleDeleteWldaMaterialFile() {
      if (this.checkedWldaMaterialFile.length == 0) {
        this.$modal.msgError("请先选择要删除的物料档案数据");
      } else {
        const wldaMaterialFileList = this.form.llslIncomingMaterialsList;
        const checkedWldaMaterialFile = this.checkedWldaMaterialFile;
        this.form.llslIncomingMaterialsList = wldaMaterialFileList.filter(function (item) {
          return checkedWldaMaterialFile.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleWldaMaterialFileSelectionChange(selection) {
      this.checkedWldaMaterialFile = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('warehouse/llrk/export', {
        ...this.queryParams
      }, `llrk_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
